package ca.nfb.media.nfbPlayer.views
{
	
	import ca.nfb.media.nfbPlayer.ComModule;
	import ca.turbulent.media.Pyro;
	import ca.turbulent.media.events.PyroEvent;
	import ca.turbulent.media.events.StatusUpdateEvent;	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.utils.Timer;
	
	public class BufferingView extends FullModalView
	{
		private var bufferCheckTimer:Timer = new Timer(400, 1);
		private var checkTime:Number = 0;
		
		public function BufferingView()
		{
			super(true, true);
			this.backgroundAlpha = 0;
			this.player.addEventListener(StatusUpdateEvent.STATUS_UPDATE, pyroStatusChanged, false, 0, true);
			bufferCheckTimer.addEventListener(TimerEvent.TIMER_COMPLETE, checkNow, false, 0, true);
		}

		
		private function pyroStatusChanged(evt:StatusUpdateEvent):void
		{
			if (evt.status == Pyro.STATUS_PENDING)
			{
				if (core.currentState != NFBPlayer.END_PLAYLIST_STATE)
					startChecking();	
			}	
			else
			{
				if (this.isRunning)
				{
					if (bufferCheckTimer.running)
						bufferCheckTimer.stop();
						
					this.visible = false;
					this.stopModal();
				}
			}
		}
		
		public function startChecking():void
		{
			if (bufferCheckTimer.running)
				bufferCheckTimer.stop();
			
			this.visible = false;
			this.stopModal();
						
			checkTime = player.time;
			bufferCheckTimer.start();

		}
		
		private function checkNow(evt:TimerEvent):void
		{
			if (player.time == this.checkTime)
			{
				bufferCheckTimer.stop();	
				this.visible = true;
				this.startModal();
			}
		}
		
		override protected function coreStateUpdated(evt:Event=null):void 
		{
			if (core.currentState == NFBPlayer.PREVIEW_IMAGE_STATE || core.currentState == NFBPlayer.FILE_NOT_FOUND_STATE)
			{
				this.visible = false;
				this.stopModal();
				
				if (bufferCheckTimer.running)
					bufferCheckTimer.stop();
			}
		}
	}
}